Developer Documentation
PATH  Mac OS X Documentation > Developer Tools > The Objective-C Compiler


Previous | Contents | Next

Accessing Instance Variables in Class Methods

It used to be common programming style in Objective-C to assign to self in a class method and then access instance variables. This is bad style because self in the context of a class method stands for the class object--and shouldn't be redefined to stand for a particular instance of the object.

Here is an example of this bad style :

@implementation Oval : Object { int x; } +new { self = [super new]; // Now self refers to a class instance ... x = 4; // Assigns an instance variable } ... @end ... x = [Oval new]; // Create an Oval object

To discourage this anachronistic use, the compiler issues a warning if an instance variable is referenced in a class method.

Here's a better way to instantiate an object:

x = [[Oval alloc] init];

See Object-Oriented Programming and the Objective C Language for more details.


The Objective-C Compiler

Previous | Contents | Next